package com.se.server;

import com.se.common.User;
import com.se.db.DbMessage;
import com.se.db.DbUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.SQLException;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

import static com.se.common.Constant.OFFLINE;
import static com.se.common.Constant.ONLINE;

public class OnlineUserManager {
    private final Map<String, Long> onlineUsers = new ConcurrentHashMap<>();
    private static final Logger logger = LoggerFactory.getLogger(OnlineUserManager.class);

    private static final OnlineUserManager instance = new OnlineUserManager();
    private OnlineUserManager(){
    }

    public static OnlineUserManager getInstance() {
        return instance;
    }

    public void userOnline(String username) {
        onlineUsers.put(username, System.currentTimeMillis());
        try {
            User user = DbUser.getInstance().getUser(username);
            user.setStatus(ONLINE);
            ServerUtils.onlineBroadCast(user);
        } catch (SQLException e) {
            logger.info("用户上线异常: {}", e.getMessage(), e);
        }
    }

    public void userOffline(String username) {
        onlineUsers.remove(username);
        Server.rmConnection(username);
        try {
            User user = DbUser.getInstance().getUser(username);
            user.setStatus(OFFLINE);
            ServerUtils.onlineBroadCast(user);
            //下线后删除所有AI解释消息
            DbMessage.getInstance().deleteAIExplainMessage(username);
        } catch (SQLException e) {
            logger.info("用户下线异常: {}", e.getMessage(), e);
        }
    }

    public Set<String> getOnlineUsers() {
        return Collections.unmodifiableSet(onlineUsers.keySet());
    }

    public void updateUserActivity(String username) {
        onlineUsers.computeIfPresent(username, (k, v) -> System.currentTimeMillis());
    }
}
